package com.sunday.shoufen.ui;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sunday.common.adapter.MainFragmentPagerAdapter;
import com.sunday.common.alipay.Base64;
import com.sunday.common.common.MemberConst;
import com.sunday.common.event.EventBus;
import com.sunday.common.event.ExitApp;
import com.sunday.common.model.ResultDO;
import com.sunday.common.model.Version;
import com.sunday.common.qrcode.CaptureActivity;
import com.sunday.common.update.UpdateDialogActivity;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.DeviceUtils;
import com.sunday.common.utils.SharePerferenceUtils;
import com.sunday.common.widgets.ViewPager;
import com.sunday.shoufen.R;
import com.sunday.shoufen.base.BaseApp;
import com.sunday.shoufen.base.MyBaseActivity;
import com.sunday.shoufen.entity.Member;
import com.sunday.shoufen.entity.Seller;
import com.sunday.shoufen.entity.ShopDetail;
import com.sunday.shoufen.http.ApiClient;
import com.sunday.shoufen.ui.index.IndexFragment;
import com.sunday.shoufen.ui.index.MineFragment;
import com.sunday.shoufen.ui.index.NearByFragment;
import com.sunday.shoufen.ui.index.OrderFragment;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.sunday.shoufen.R.mipmap.member;
import static com.sunday.shoufen.R.mipmap.serach;

public class MainActivity extends MyBaseActivity {

    @Bind(R.id.tab1)
    TextView tab1;
    @Bind(R.id.tab2)
    TextView tab2;
    @Bind(R.id.tab3)
    TextView tab3;
    @Bind(R.id.tab4)
    TextView tab4;

    @Bind(R.id.content)
    ViewPager viewPager;
    @Bind(R.id.scan)
    ImageView scan;

    private ArrayList<TextView> tabViews = new ArrayList<>();
    private ArrayList<Fragment> fragments;
    private Member member;
    private int page;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        checkLogin();
        checkUpdate();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow()
                    .getDecorView()
                    .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        } else {
            getWindow()
                    .setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        initFragments();


    }

    @Override
    public boolean needLocationPermission() {
        return true;
    }

    @Override
    public boolean needSdCardPermission() {
        return true;
    }

    private void checkLogin() {
        boolean login = SharePerferenceUtils.getIns(mContext).getBoolean(Constants.IS_LOGIN, false);
        if (!login) {
            intent = new Intent(mContext, LoginActivity.class);
            startActivity(intent);
            finish();
        } else {
            member = (Member) SharePerferenceUtils.getIns(mContext).getOAuth();
            if (member != null) {
                BaseApp.getInstance().setMember(member);
            }
        }

    }


    private void initFragments() {
        tabViews.add(tab1);
        tabViews.add(tab2);
        tabViews.add(tab3);
        tabViews.add(tab4);
        fragments = new ArrayList<>(4);
        fragments.add(IndexFragment.newInstance());
        fragments.add(NearByFragment.newInstance());
        fragments.add(OrderFragment.newInstance());
        fragments.add(MineFragment.newInstance());
        viewPager.setAdapter(new MainFragmentPagerAdapter(getSupportFragmentManager(), fragments));
        viewPager.setOffscreenPageLimit(4);
        viewPager.setCurrentItem(0, false);
        tabViews.get(0).setSelected(true);
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < tabViews.size(); i++) {
                    tabViews.get(i).setSelected(false);
                }
                tabViews.get(position).setSelected(true);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @OnClick({R.id.tab1, R.id.tab2, R.id.tab3, R.id.tab4, R.id.scan})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tab1:
                viewPager.setCurrentItem(0, false);
                break;
            case R.id.tab2:
                viewPager.setCurrentItem(1, false);
                break;
            case R.id.tab3:
                viewPager.setCurrentItem(2, false);
                break;
            case R.id.tab4:
                viewPager.setCurrentItem(3, false);
                break;
            case R.id.scan:
                checkCameraPermission();
                if (isRequestCameraPermission()) {
                    Intent intent = new Intent(mContext, CaptureActivity.class);
                    startActivityForResult(intent, 1);
                }
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case 1:
                Gson gson = new Gson();
                String result = new String(Base64.decode(data.getStringExtra("result")));
                Seller shopDetail = gson.fromJson(result, Seller.class);
                intent = new Intent(mContext, ShopDetailActivity.class);
                intent.putExtra("shopId", shopDetail.getSellerId());
                startActivity(intent);
                break;
        }

    }

//    @Override
//    public boolean onRequestLocPermissionSuccessed() {
//        return true;
//
//    }
//
//    @Override
//    public boolean onRequestCameraPemissionSucceed() {
//        return true;
//    }


    @Override
    public void onLocSucceed() {

    }

    @Override
    public void onLocFailed() {
        //requestLocation();
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(mContext, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                EventBus.getDefault().post(new ExitApp());
                System.exit(1);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    private void checkUpdate() {
        Call<ResultDO<Version>> call = ApiClient.getApiAdapter().checkVersion(MemberConst.USER, DeviceUtils.getVersionCode(getApplicationContext()));
        call.enqueue(new Callback<ResultDO<Version>>() {
            @Override
            public void onResponse(Call<ResultDO<Version>> call, Response<ResultDO<Version>> response) {
                ResultDO<Version> resultDO = response.body();
                if (isFinish) {
                    return;
                }
                if (resultDO != null && resultDO.getCode() == 0) {
                    final Version version = resultDO.getResult();
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = new Intent(mContext, UpdateDialogActivity.class);
                            intent.putExtra("version", version);
                            startActivity(intent);
                        }
                    }, 2000);
                }
            }

            @Override
            public void onFailure(Call<ResultDO<Version>> call, Throwable t) {

            }
        });
    }

}
